package com.wqnmdb.im.service.redis;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * redis hash 服务
 * 可用于用户中奖纪录
 *
 * @author 王欣
 */
@Service
public class RedisHashService {

    private static final Logger logger = LoggerFactory.getLogger(RedisHashService.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void delKey(String key) {
        logger.debug("delKey().params:" + key);
        stringRedisTemplate.delete(key);
    }

    /**
     * 入
     *
     * @param key
     * @param value
     * @return
     */
    public void put(String key, String attribute, String value) {
        stringRedisTemplate.opsForHash().put(key, attribute, value);
    }

    /**
     * 随机选一个
     *
     * @param key
     * @return
     */
    public String get(String key, String attribute) {
        return (String) stringRedisTemplate.opsForHash().get(key, attribute);
    }

    /**
     * 返回jsonObject
     * @param key
     * @param attribute
     * @return
     */
    public JSONObject getJson(String key, String attribute) {
        String str =  (String) stringRedisTemplate.opsForHash().get(key, attribute);
        if(StringUtils.isNotBlank(str)){
            return JSONObject.parseObject(str);
        }
        return null;
    }

    /**
     * 大小
     *
     * @param key
     * @return
     */
    public Long size(String key) {
        return stringRedisTemplate.opsForHash().size(key);
    }

    /**
     * 是否包含指定成员
     *
     * @param key
     * @param attribute
     * @return
     */
    public Boolean hasKey(String key, String attribute) {
        return stringRedisTemplate.opsForHash().hasKey(key, attribute);
    }

    /**
     * 删除指定元素
     *
     * @param key
     * @param attribute
     */
    public void remove(String key, String attribute) {
        stringRedisTemplate.opsForHash().delete(key, attribute);
    }

    /**
     * 得到所有的key
     *
     * @param key
     * @return
     */
    public Set<Object> keys(String key) {
        return stringRedisTemplate.opsForHash().keys(key);
    }

}


